<template>
	<view class="ff-tabbar" v-show="children.length > 1?true:isSingleDisplay" :style="[tabbarStyle]">
		<slot name="default"></slot>
	</view>
</template>

<script>
	export default {
		name: "ff-tabbar",
		emits: ["update:modelValue", "input", "change"],
		emits: ['before-leave'],
		options: {
			styleIsolation: 'isolated',
			virtualHost: true
		},
		props: {
			value: {
				type: [String, null],
				default: undefined
			},
			modelValue: {
				type: [String, null],
				default: undefined
			},
			isSingleDisplay: {
				type: Boolean,
				default: undefined
			},
			bgColor: {
				type: String,
				default: undefined
			},
			borderColor: {
				type: String,
				default: undefined
			},
			options: {
				type: Array,
				default: undefined
			},
		},
		data() {
			return {
				children: [],
			}
		},
		provide() {
			return {
				ffTabbar: {
					getValue: this.getValue,
					setValue: this.setValue,
					addChildren: this.addChildren,
					removeChildren: this.removeChildren,
				},
			}
		},
		computed: {
			model: {
				get() {
					return this.getValue()
				},
				set(newValue) {
					this.setValue(newValue)
				}
			},
			tabbarStyle() {
				let style = {
					borderTop: `1px solid ${this.$ff.props.borderColor}`,
					backgroundColor: this.bgColor,
				}
				style['paddingBottom'] = this.$ff.safeAreaInsets.bottom + 'px'
				style['height'] = `calc(${style['paddingBottom']} + 115rpx)`
				if (this.$ff.component.parent && this.$ff.component.parent.$ff.name === "ff-windows") {
					this.$set(this.$ff.component.parent.$ff.config.props, 'ff-windows', {
						bottomHeight: style['height'],
					})
				}
				return style
			},
		},
		mounted() {

		},
		// #ifdef VUE2
		destroyed() {

		},
		// #endif
		// #ifdef VUE3
		unmounted() {

		},
		// #endif
		methods: {
			getValue() {
				// #ifdef VUE2
				return this.value
				// #endif

				// #ifdef VUE3
				return this.modelValue
				// #endif
			},
			setValue(val) {
				this.$emit("input", val)
				this.$emit("update:modelValue", val)
				this.$emit("change", val)
			},
			addChildren(item) {
				for (let i = 0; i < this.children.length; i++) {
					if (this.children[i].$ff.id === item.$ff.id) {
						return
					}
				}
				this.children.push(item)
				this.children.sort((a, b) => b.sort - a.sort)
				if (this.getValue() === null || this.getValue() === "") {
					if (this.children.length === 1) {
						this.setValue(item.name)
					} else if (item.isDefault) {
						this.setValue(item.name)
					}
				}
			},
			removeChildren(item) {
				for (let i = 0; i < this.children.length; i++) {
					if (this.children[i].$ff.id === item.$ff.id) {
						this.children.splice(i, 1)
					}
				}
			},
		},
	}
</script>

<style scoped>
	@import "../../librarys/css/components.css";

	.ff-tabbar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		align-content: center;
		flex-direction: row;
		flex-wrap: nowrap;
		width: 100%;
	}
</style>